package com.learn.LinkedTable;


public class LinkedTableDemo {

    /**
     * 反转单链表
     *
     * @param head
     */
    public Node reverseNode(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    /**
     * 删除链表中指定的数
     *
     * @param head
     * @param num
     * @return
     */
    public Node deleteNumNode(Node head, int num) {
        //寻找表头不为num的数
        while (head != null) {
            if (head.value != num) {
                break;
            }
            head = head.next;
        }
        Node pre = head;
        Node cur = head;
        while (head != null) {
            if (cur.value == num) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }


        return head;

    }


    //判断单链表是否有环，有环则返回入环点，先通过快慢指针找到第一次相遇的点，然后在让快指针回到head,然后每次走一步
    public Node findLoopNode(Node head) {
        if (head == null || head.next == null || head.next.next == null) {
            return null;
        }
        Node fast = head.next;
        Node slow = head.next.next;

        while (fast != slow) {
            if (fast.next == null || fast.next.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }

        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;


    }


    public static class Node {
        public int value;
        public Node next;

        public Node(int value) {
            this.value = value;
        }
    }
}
